#include "mem_sal.h"
#include "mem_inner.h"
#if defined (CONFIG_OS_ENABLE)
#include "os_sal.h"
#endif


/* 内存管理 */


#if CONFIG_MEM_ENABLE

/* static var */

#if defined (CONFIG_MEM_TYPE_TLSF)
extern _mem_sal_opt mem_tlsf_sal_opt;
static const _mem_sal_opt *mem_sal_opt = &mem_tlsf_sal_opt;
// static const char *mem_type_name = "TLSF";
#elif defined (CONFIG_MEM_TYPE_FREERTOS)
extern const _mem_sal_opt mem_free4_sal_opt;
static const _mem_sal_opt *mem_sal_opt = &mem_free4_sal_opt;
// static const char *mem_type_name = "FreeRTOS-heap4";
#elif defined (CONFIG_MEM_TYPE_RTX5)
extern const _mem_sal_opt mem_rtx5_sal_opt;
static const _mem_sal_opt *mem_sal_opt = &mem_rtx5_sal_opt;
// static const char *mem_type_name = "RTX5";
#elif defined (CONFIG_MEM_TYPE_THREADX)
extern const _mem_sal_opt mem_tx_sal_opt;
static const _mem_sal_opt *mem_sal_opt = &mem_tx_sal_opt;
// static const char *mem_type_name = "Threadx";
#else
  #error "memory type not support!"
#endif


#if defined (CONFIG_OS_ENABLE)
static os_mutex_handle_t mem_mutex = NULL;
#endif

/* export func */

void mem_lock(void)
{
#if defined (CONFIG_OS_ENABLE)
    os_mutex_take(mem_mutex, OS_WAIT_MAX);
#endif
}

void mem_unlock(void)
{
#if defined (CONFIG_OS_ENABLE)
    os_mutex_release(mem_mutex);
#endif
}

/**
 * @brief 初始化
 * 
 */
void mem_init(void)
{
#if defined (CONFIG_OS_ENABLE)
    mem_mutex = os_mutex_create();
    printf("mem_mutex = 0x%08X\r\n", mem_mutex);
#endif

#if CONFIG_MEM_AREA_DTCM_ENABLE
    mem_dtcm_init();
#endif

#if CONFIG_MEM_AREA_AXI_ENABLE
    mem_axi_init();
#endif

#if CONFIG_MEM_AREA_SRAM1_ENABLE
    mem_sram1_init();
#endif

#if CONFIG_MEM_AREA_SRAM2_ENABLE
    mem_sram2_init();
#endif

}

/**
 * @brief 内存释放
 * 
 * @param ptr 
 */
void mem_free(void *ptr)
{
    mem_dtcm_free(ptr);
}

/**
 * @brief 内存申请
 * 
 * @param bytes 
 * @return void* 
 */
void *mem_malloc(size_t bytes)
{
    return mem_dtcm_malloc(bytes);
}

/**
 * @brief 内存重置
 * 
 * @param ptr 
 * @param bytes 
 * @return void* 
 */
void *mem_realloc(void *ptr, size_t bytes)
{
    return mem_dtcm_realloc(ptr, bytes);
}

/**
 * @brief 块内存申请
 * 
 * @param cnt 
 * @param bytes 
 * @return void* 
 */
void *mem_calloc(size_t cnt, size_t bytes)
{
    return mem_dtcm_calloc(cnt, bytes);
}

/**
 * @brief 内存使用情况
 * 
 * @param info 
 */
void mem_get_info(_mem_sal_info_t *info)
{
    mem_dtcm_get_info(info);
}

/**
 * @brief 内存算法名
 * 
 * @return char* 
 */
char *mem_get_name(void)
{
    return mem_dtcm_get_name();
}

/**
 * @brief 获取内存操作句柄
 * 
 * @return _mem_sal_opt* 
 */
_mem_sal_opt *mem_get_opt(void)
{
    return (_mem_sal_opt*)mem_sal_opt;
}



#endif  // CONFIG_MEM_ENABLE




